#include <windows.h>
#include <stdio.h>
#include "include/pointers.h"

#define OPCODES			"\x80\x86\x3e\x03\x00\x00\x01"	//ADD BYTE PTR [ESI + 33E], 1
#define PATCHED			"\x80\x86\x3e\x03\x00\x00\x00"	//ADD BYTE PTR [ESI + 33E], 0

int main(int argc, char **argv)
{
	HANDLE		rom_process;
	DWORD		old_protect;

	int		        rom_pid;
	unsigned char	instructions[7];
	char		   *new_instructions = NULL;

	/* get pid */
	if(argc < 2)
	{
		printf("If you don't know what this is or where to find it read the readme file.\nEnter the RoM process ID: ");
		scanf("%d", &rom_pid);
	}
	else
	{
		sscanf(argv[1], "%d", &rom_pid);
	}
	
	/* open process for reading & writing */
	rom_process = OpenProcess(PROCESS_VM_READ | PROCESS_VM_WRITE | PROCESS_VM_OPERATION, 0, rom_pid);
	if(rom_process == NULL)
	{
		fprintf(stderr, "Error: Could not open process with pid %d (error %lu)\n", rom_pid, GetLastError());
		return 1;
	}
	
	/* Read the instructions */
	if(ReadProcessMemory(rom_process, (void *)STEALTHHACK_PTR, instructions, 7, 0) == 0)
	{
		fprintf(stderr, "Error: Failed to read the instructions from memory (error %lu)\n", GetLastError());
		return 1;
	}
	
	/* Do we need to load or unload the hack? */
	if(memcmp(OPCODES, instructions, 7) == 0)
	{
		new_instructions = PATCHED;
		printf("Trying to load hack...");
	}
	else if(memcmp(PATCHED, instructions, 7) == 0)
	{
		new_instructions = OPCODES;
		printf("Trying to un-load hack...");
	}
	else
	{
		fprintf(stderr, "Error: The instructions in memory dont match up, game version mismatch?\n");
		return 1;
	}

	/* Make the instructions writeable */
	if(VirtualProtectEx(rom_process, (void *)STEALTHHACK_PTR, 7, PAGE_READWRITE, &old_protect) == 0)
	{
		fprintf(stderr, "Error: Failed to change the memory access rights (error %lu)\n", GetLastError());
		return 1;

	}

	/* Patch up! */
	if(WriteProcessMemory(rom_process, (void *)STEALTHHACK_PTR, new_instructions, 7, NULL) == 0)
	{
		fprintf(stderr, "\nError: Failed to write the instructions to memory (error %lu)\n", GetLastError());
		return 1;
	}

	/* restore memory access rights */
	if(VirtualProtectEx(rom_process, (void *)STEALTHHACK_PTR, 7, old_protect, &old_protect) == 0)
	{
		fprintf(stderr, "Error: Failed to change the memory access rights (error %lu)\n", GetLastError());
		return 1;

	}

	printf(" Done!\n");
	return 0;
}

